// marks.js
var util = require('../../utils/util.js');
var app = getApp();
var bibleData = require('../../utils/bible.js')
var glo = require('../../utils/global.js')
var config = require('../../utils/config.js')
var oldbook = "";
var newbook = "";
var lastTapDiffTime = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ["全部"],
    bookSel: "0",
    index: 0,
    favArr: [],
    oFav: [],
    verseArr: [],
    isedit: false,
    userInfo: null,
    pageCount: 8,
    noMore: false,
    bversion: config.bversion
  },
  tapedit: function() {
    var bool = this.data.isedit;
    this.setData({
      isedit: !bool
    });
  },
  changType: function(e) {
    var num = e.target.dataset.num
    var arr = this.data.favArr;
    arr[num][3] = !arr[num][3];
    this.setData({
      favArr: arr
    });
  },
  allChangeType: function() {
    var arr = this.data.favArr;
    var arr02 = arr.filter(function(item, index) {
      return item[3] == true;
    })
    if (arr02.length == arr.length) {
      arr.forEach(function(item, index) {
        arr[index][3] = false;
      });
    } else {
      arr.forEach(function(item, index) {
        arr[index][3] = true;
      });
    }
    this.setData({
      favArr: arr
    });
  },
  delType: function() {
    var that = this;
    var favArr = this.data.favArr;
    var delArr = [];
    var arr = favArr.filter(function(item, index) {
      return item[3] == true;
    })
    if (arr.length > 0) {
      wx.showModal({
        title: '删除提示',
        content: '确认是否删除该记录',
        success: function() {
          var str = '';
          arr.forEach(function(item) {
            var delStr = ';#' + item[1].replace(/\||\:/g, '-') + '#';
            str += delStr;
            delArr.push(delStr)
          });
          wx.request({
            url: glo.https + '/person/fav_update1',
            data: {
              edit_fav: str,
              addordel: 'del',
              userid: that.data.userInfo.userId
            },
            success: function(res2) {
              var favorite = that.data.userInfo.favorite;
              delArr.forEach(
                function(item) {
                  favorite = favorite.replace(item, "");
                }
              );
              //  favorite = favorite.replace(str, "");
              that.data.userInfo.favorite = favorite;
              app.setUserInfo(that.data.userInfo);
              that.tapedit();
              that.loadFav();
              //console.log(res2)
            }
          })
        }
      });
    } else {
      wx.showToast({
        title: '请选择你要删除的记录',
        icon: 'none'
      });
    }
  },
  radioChange: function(e) {
    var v = e.detail.value
    var array1 = ["全部"];
    if (v == "0") {
      array1 = ["全部"];
    } else if (v == "1") {
      for (var i = 0; i < oldbook.length; i++) {
        array1.push(oldbook[i].bookName);
      }
    } else {
      for (var i = 0; i < newbook.length; i++) {
        array1.push(newbook[i].bookName);
      }

    }

    this.setData({
      bookSel: v,
      array: array1,
      index: 0
    });
    this.selectMarks();
  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    });
    this.selectMarks();
  },

  transArrData: function(verseArr, favArr) {
    var that = this;
    var chapterArr = new Array();
    for (var i = 0; i < verseArr.length; i++) {
      var id = verseArr[i].bookId + "-" + verseArr[i].chapterId;
      if (chapterArr.indexOf(id) == -1) {
        var verIndexArr = new Array();
        var verContentArr = new Array();
        chapterArr.push(id);
        for (var j = 0; j < verseArr.length; j++) {
          var id1 = verseArr[j].bookId + "-" + verseArr[j].chapterId;
          if (id1 == id) {
            verIndexArr.push(verseArr[j].verseId);
            verContentArr.push(verseArr[j].content);
            var bookId = parseInt(verseArr[j].bookId);
            var chapterId = verseArr[j].chapterId;
            var bookName = '';
            if (bookId > 39) {
              bookName = newbook[bookId - 40].bookName
            } else {
              bookName = oldbook[bookId - 1].bookName
            }
            var selIndexs = new Array();
            var selChapters = new Array();
            var selContents = new Array();
            that.getSelVerses0(bookName, bookId, chapterId, verIndexArr, verContentArr, selIndexs, selChapters, selContents)
          }
        }
        for (var a0 = 0; a0 < selIndexs.length; a0++) {
          var arr0 = new Array();
          arr0[0] = selIndexs[a0];
          arr0[1] = selChapters[a0];
          arr0[2] = selContents[a0];
          arr0[3] = false;
          favArr.push(arr0);
        }

      }
    }
  },
  lower: function(e) {
    if (this.data.noMore || this.data.favArr.length === 0) {
      return;
    }
    let that = this,
      oFav = this.data.oFav,
      pageArr = [],
      pageCount = this.data.pageCount;

    for (let i = 0; i < pageCount; i++) {
      if (oFav[i] !== undefined) {
        pageArr.push(oFav[i]);
      } else {
        that.setData({
          noMore: true
        });
        break;
      }
    }
    this.setData({
      favArr: pageArr,
      pageCount: pageCount + 8,
    });
  },

  loadFav: function(option) {
    var res = wx.getSystemInfoSync();
    var screenH = res.windowHeight;
    var that = this;
    var pageCount = this.data.pageCount;
    var pageArr = [];
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo) {
      var verseArr = [];
      var favArr = new Array();
      var favorite = userInfo.favorite.replace(/#/g, "");

      wx.request({
        url: glo.https + '/person/getfav?fav=' + favorite,
        method: 'GET',
        success: function(res) {
          verseArr = res.data;
          that.transArrData(verseArr, favArr);

          for (let i = 0; i < pageCount; i++) {
            if (favArr[i] !== undefined) {
              pageArr.push(favArr[i]);
            } else {
              that.setData({
                noMore: true
              });
              break;
            }
          }
          that.setData({
            userInfo: userInfo,
            favArr: pageArr,
            oFav: favArr,
            pageCount: pageCount + 8,
            screenH: screenH,
            verseArr: verseArr
          });
          wx.hideLoading();
        },
        fail: function(res) {
          wx.hideLoading();
          wx.showToast({
            title: '加载失败，请检查网络',
            icon: 'loading',
            duration: 1000
          })
        }
      });

    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    oldbook = bibleData.oldbooks;
    newbook = bibleData.newbooks;
    this.loadFav(options);
    wx.hideShareMenu();
  },

  selectMarks: function() {
    var that = this;
    var arrdata0 = this.data.verseArr;
    var arrdata = [];
    var bookSel = that.data.bookSel;
    var bookIndex = that.data.index;
    if (bookSel == "0") { //全部范围
      arrdata = arrdata0;
    } else if (bookSel == "1") { //范围

      for (var i = 0; i < arrdata0.length; i++) {
        if (arrdata0[i].bookId <= 39) {
          if (bookIndex == 0) {
            arrdata.push(arrdata0[i]);
          }
          var theBookId = parseInt(arrdata0[i].bookId);
          if (theBookId == bookIndex) {
            arrdata.push(arrdata0[i]);
          }

        }
      }

    } else { //范围
      for (var i = 0; i < arrdata0.length; i++) {
        if (arrdata0[i].bookId > 39) {
          if (bookIndex == 0) {
            arrdata.push(arrdata0[i]);
          }
          var theBookId = parseInt(arrdata0[i].bookId);
          if (theBookId == parseInt(bookIndex) + 39) {
            console.log(theBookId);
            arrdata.push(arrdata0[i]);
          }

        }
      }
    }
    var favArr = new Array();
    that.transArrData(arrdata, favArr);
    that.setData({
      favArr: favArr
    });
  },

  catalogUrl: function(e) {
    var curTime = e.timeStamp;
    var lastTime = lastTapDiffTime;
    if (lastTime > 0) {
      if (curTime - lastTime < 300) {
        console.log("双击事件");
        lastTapDiffTime = curTime;
        return;
      }
    }
    lastTapDiffTime = curTime;

    console.debug("开启一页，锁定");
    var vid = e.target.dataset.id;
    var arr1 = vid.split(':');
    var arr2 = arr1[0].split('|');
    var arr3 = arr1[1].split('-');
    var verseid = arr3[0];
    var bookId = parseInt(arr2[0]);
    var chapterId = arr2[1];
    var bookName = "";
    var chapterCount = 0;
    if (bookId > 39) {
      bookName = newbook[bookId - 40].bookName;
      chapterCount = newbook[bookId - 40].chapterCount;
    } else {
      bookName = oldbook[bookId - 1].bookName;
      chapterCount = oldbook[bookId - 1].chapterCount;
    }
    var content = "";
    var keyid = "CH" + "-" + bookId + "-" + chapterId;

    wx.getStorage({
      key: "bk" + bookId,
      success: function(res) {
        wx.showLoading({
          title: "正在加载...",
          mask: true
        });
        var bookData = res.data;
        for (var i = 0; i < bookData.length; i++) {
          if (chapterId == bookData[i].chapterId) {
            content = bookData[i].content;
            console.log("缓存读取" + bookName + "第" + chapterId + "章");
            wx.navigateTo({
              url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content + '&lid=' + verseid,
              success: function(res) {
                wx.hideLoading();
                // success
              },
              fail: function() {
                wx.hideLoading();
                // fail
              }
            })
          }
        }
      },
      fail: function() {
        wx.showLoading({
          title: "首次加载该卷",
          mask: true
        });
        wx.request({
          url: glo.https + '/chapter/list_bookid?bookId=' + bookId,
          method: 'GET',
          success: function(res) {
            wx.setStorage({ //添加缓存
              key: "bk" + bookId,
              data: res.data
            });
            var bookData = res.data;
            for (var i = 0; i < bookData.length; i++) {
              if (chapterId == bookData[i].chapterId) {
                content = bookData[i].content;
                console.log("缓存读取" + bookName + "第" + chapterId + "章");
                wx.navigateTo({
                  url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content + '&lid=' + verseid,
                  success: function(res) {
                    wx.hideLoading();
                    // success
                  },
                  fail: function() {
                    wx.hideLoading();
                    wx.showToast({
                      title: '加载失败，请检查网络',
                      icon: 'loading',
                      duration: 1000
                    })
                    // fail
                  }
                })
              }
            }
          }
        })
      }
    });
  },

  getSelVerses: function(bookName, bookId, chapterId, verIndexArr, verContentArr, selIndexs, selChapters, selContents) {
    var minx = -1;
    var maxx = -1;
    var maxmin = new Array();
    var nn = 0;
    var index = verIndexArr.length;
    for (var i = 0; i < index; i++) {
      if (minx == -1) {
        minx = verIndexArr[i];
        maxx = verIndexArr[i];
      }
      if (i + 1 < index) {
        if (verIndexArr[i + 1] - verIndexArr[i] == 1) {
          maxx = verIndexArr[i + 1];
        } else {
          maxmin[nn] = new Array();
          maxmin[nn][0] = minx;
          maxmin[nn][1] = maxx;
          nn = nn + 1;
          minx = -1;
          maxx = -1;
        }
      } else {
        maxmin[nn] = new Array();
        maxmin[nn][0] = minx;
        maxmin[nn][1] = maxx;
      }
    }
    var bname = bookName;
    var bid = bookId;
    var cid = chapterId;
    var kn = 0;
    var selN = 0;
    for (var k = 0; k <= nn; k++) {
      var ma = maxmin[k][0];
      var mb = maxmin[k][1];
      if (ma == mb) {
        selChapters[selN] = bid + "|" + cid + ":" + ma;
        selContents[selN] = verContentArr[kn];
        selIndexs[selN] = bname + cid + ":" + ma;
        selN = selN + 1
        kn = kn + 1;
      } else {
        var ln = mb - ma + 1;
        var cnten = "";
        for (var kd = 0; kd < ln; kd++) {
          cnten = cnten + verContentArr[kn + kd];
        }
        kn = kn + ln;
        selChapters[selN] = selChapters[selN] = bid + "|" + cid + ":" + ma + "-" + mb;
        selContents[selN] = cnten;
        selIndexs[selN] = bname + cid + ":" + ma + "-" + mb;
        selN = selN + 1;
      }
    }
  },

  getSelVerses0: function(bookName, bookId, chapterId, verIndexArr, verContentArr, selIndexs, selChapters, selContents) {
    var minx = -1;
    var maxx = -1;
    var maxmin = new Array();
    var nn = 0;
    var index = verIndexArr.length;
    for (var i = 0; i < index; i++) {
      if (minx == -1) {
        minx = verIndexArr[i];
        maxx = verIndexArr[i];
      }
      if (i + 1 < index) {
        // if (verIndexArr[i + 1] - verIndexArr[i] == 1) {
        //    maxx = verIndexArr[i + 1];
        //  } else {
        maxmin[nn] = new Array();
        maxmin[nn][0] = minx;
        maxmin[nn][1] = maxx;
        nn = nn + 1;
        minx = -1;
        maxx = -1;
        //  }
      } else {
        maxmin[nn] = new Array();
        maxmin[nn][0] = minx;
        maxmin[nn][1] = maxx;
      }
    }
    var bname = bookName;
    var bid = bookId;
    var cid = chapterId;
    var kn = 0;
    var selN = 0;
    for (var k = 0; k <= nn; k++) {
      var ma = maxmin[k][0];
      var mb = maxmin[k][1];
      if (ma == mb) {
        selChapters[selN] = bid + "|" + cid + ":" + ma;
        selContents[selN] = verContentArr[kn];
        selIndexs[selN] = bname + cid + ":" + ma;
        selN = selN + 1
        kn = kn + 1;
      } else {
        var ln = mb - ma + 1;
        var cnten = "";
        for (var kd = 0; kd < ln; kd++) {
          cnten = cnten + verContentArr[kn + kd];
        }
        kn = kn + ln;
        selChapters[selN] = selChapters[selN] = bid + "|" + cid + ":" + ma + "-" + mb;
        selContents[selN] = cnten;
        selIndexs[selN] = bname + cid + ":" + ma + "-" + mb;
        selN = selN + 1;
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.showLoading({
      title: "正在加载...",
      mask: true
    });
    this.onLoad(null);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function() {

  }
})